import java.io.File;
import java.io.FileWriter;
import java.net.InetAddress;

/**
 * Created by LLAP on 2017/12/10.
 * Copyright (c) 2017 LLAP. All rights reserved.
 */
public class Logger {
    private File logFile;
    private int workerID;
    private IDGenerator id;
    private FileWriter fout;
    private boolean writable = false;

    public Logger(String name) {
        try {
            workerID = Integer.parseInt(InetAddress.getLocalHost().getHostAddress().split("\\.")[3]) & 0x3ff;
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
            workerID = 0;
        }
        id = new IDGenerator(workerID);
        String filename = name + workerID + "." + id.generate() + ".log";
        logFile = new File(filename);

        if (!logFile.exists()) {
            try {
                writable = logFile.createNewFile();
            }
            catch (Exception e) {
                System.out.println(e.getMessage());
            }
            if (!writable) {
                System.out.println("Log failed.");
            }
        }
        System.out.println(name + " log at " + logFile.getAbsolutePath());
    }

    public void log(String message) {
        try {
            fout = new FileWriter(logFile.getName(), true);
            fout.write("[" + id.generate() + "] " + message + "\n");
            fout.close();
            fout = null;
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

}
